package com.cloud.wms.ui.sort.car;


import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.utils.NumberUtils;
import com.cloud.core.widget.decoration.GridItemDecoration;
import com.cloud.widget.ScanText;
import com.cloud.widget.utils.DensityUtils;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseBarListActivity;
import com.cloud.wms.config.IntentKey;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.ui.sort.contract.CarSortDetachContract;
import com.cloud.wms.ui.sort.entity.BindInfoEntity;
import com.cloud.wms.ui.sort.presenter.CarSortDetachPresenter;
import com.cloud.wms.ui.sort.sku.SkuSortActivity;
import com.cloud.wms.widget.dialog.AlertDialogBuilder;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author:Chen
 * @Date: 2021-03-01 16:51
 * @Description:
 */
public class CarBindDetachActivity extends BaseBarListActivity<BindInfoEntity, CarSortDetachPresenter> implements CarSortDetachContract.View {

    @BindView(R.id.scan_text)
    ScanText scanText;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.ll_btn)
    LinearLayout llBtn;
    private ArrayList<BindInfoEntity> infoList;
    private boolean state;
    private TaskEntity taskEntity;
    private boolean isAdd;

    @Override
    protected String barTitle() {
        return "笼车-边拣边分";
    }

    @Override
    protected int getResId() {
        return R.layout.activity_sort_car_detach_bind;
    }

    @Override
    protected int getItemResId() {
        return R.layout.item_sort_detach_bind;
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        initScanText(scanText);
        taskEntity = getIntent().getParcelableExtra(IntentKey.TASK_KEY);
        isAdd = getIntent().getBooleanExtra(IntentKey.TYPE_KEY, false);
        if (!isAdd)
            mPresenter.checkBindContainer(taskEntity.getMainBillID());
        mAdapter.addChildClickViewIds(R.id.iv_delete);
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()) {
                case R.id.iv_delete:
                    if (state) {
                        info("当前任务已绑定容器，不可删除！");
                        return;
                    }
                    onAlert("是否删除？", (dialog, which) -> {
                        adapter.removeAt(position);
                        success("删除成功！");
                    });
                    break;
            }
        });
    }

    @Override
    public void onReload() {
        super.onReload();
        mPresenter.checkBindContainer(taskEntity.getMainBillID());
    }


    @Override
    protected void onScanHandle(String result, int resultCode) {
        super.onScanHandle(result, resultCode);
        scanText.addHistory(result);
        mPresenter.checkContainer(state, (ArrayList<BindInfoEntity>) mAdapter.getData(), result);
    }

    @Override
    protected RecyclerView.LayoutManager getLayoutManager() {
        return new GridLayoutManager(this, 3);
    }

    @Override
    protected RecyclerView.ItemDecoration itemDecoration() {
        return GridItemDecoration.newBuilder().spanCount(3)
                .verticalDivider(ContextCompat.getDrawable(this, R.color.bg_base_content), DensityUtils.Dp2Px(this, 6), false)
                .horizontalDivider(ContextCompat.getDrawable(this, R.color.bg_base_content), DensityUtils.Dp2Px(this, 6), false)
                .build();
    }

    @Override
    protected void bindItemData(BaseViewHolder helper, BindInfoEntity item) {
        helper.setText(R.id.tv_container_num, (NumberUtils.getIntegerValue(item.getBindNum()) > 0 ? item.getBindNum() : (helper.getAdapterPosition() + 1)) + "号")
                .setText(R.id.tv_container_code, (TextUtils.isEmpty(item.getContainerCode()) ? "待绑定" : item.getContainerCode()))
                .setVisible(R.id.label_view, item.isState())
                .setVisible(R.id.iv_delete, !state && !TextUtils.isEmpty(item.getContainerCode()));
    }

    @Override
    protected void setupComponent() {
        getActivityComponent().inject(this);
    }

    @Override
    public void onSuccess(Message message) {
        super.onSuccess(message);
        switch (message.what) {
            case CarSortDetachPresenter.CHECK_BIND_CONTAINER:
                infoList = ((ArrayList<BindInfoEntity>) message.obj);
                if (infoList.size() == 0)
                    return;
                BindInfoEntity bindInfoEntity = infoList.get(infoList.size() - 1);
                if (bindInfoEntity.getContainerID() > 0 || !TextUtils.isEmpty(bindInfoEntity.getContainerCode())) {
                    info("当前任务已绑定容器，请扫描确认！");
                    state = true;
                } else if (bindInfoEntity.isPrintOrder()) {
                    new AlertDialogBuilder(this)
                            .setTitle("提示")
                            .setMessage("检测当前面单已打印，是否跳过容器操作？")
                            .setPositiveButton("跳过", (dialog, which) -> {
                                SkuSortActivity.start(CarBindDetachActivity.this, new BindInfoEntity(), taskEntity);
                                finish();
                            })
                            .setNegativeButton("取消", null)
                            .show();
                    llBtn.setVisibility(View.VISIBLE);
                } else {
                    info("请绑定容器！");
                    llBtn.setVisibility(View.VISIBLE);
                }
                mAdapter.setNewInstance(infoList);
                break;
            case CarSortDetachPresenter.CHECK_CONTAINER:
                mAdapter.notifyDataSetChanged();
                btnSubmit.setEnabled(((boolean) message.obj));
                break;
            case CarSortDetachPresenter.VERIFY_CONTAINER:
            case CarSortDetachPresenter.BIND_CONTAINER:
                CarSortDetachActivity.start(this, taskEntity);
                this.finish();
                break;
        }
    }

    @OnClick(R.id.btn_submit)
    public void onViewClicked() {
        mPresenter.bindContainer(taskEntity.getMainBillID(), infoList);
    }

    public static void start(Context context, TaskEntity taskEntity, boolean isAdd) {
        Intent intent = new Intent(context, CarBindDetachActivity.class);
        intent.putExtra(IntentKey.TASK_KEY, taskEntity);
        intent.putExtra(IntentKey.TYPE_KEY, isAdd);
        context.startActivity(intent);
    }
}
